package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.commom.CustomException;
import com.example.config.R;
import com.example.dao.CategoryDao;
import com.example.entity.Category;
import com.example.entity.Dish;
import com.example.entity.Setmeal;
import com.example.service.CategoryService;
import com.example.service.DishService;
import com.example.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, Category> implements CategoryService {
    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    @Override
    public Page<Category> findPage(Page<Category> page1, LambdaQueryWrapper<Category> queryWrapper) {
        return  categoryDao.selectPage(page1, queryWrapper);

    }

    @Override
    public void add(Category category) {
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        categoryDao.insert(category);

    }

    @Override
    public R findById(Long id) {
        Category category=categoryDao.selectById(id);
        return R.success(category);
    }

    @Override
    public void updateCategory(Category category) {
        category.setUpdateTime(LocalDateTime.now());//获取最后修改的时间
        categoryDao.updateById(category);
    }

    @Override
    public void delete(Long id) {
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Dish::getCategoryId,id);
        int count=dishService.count(queryWrapper);
        if (count>0){
            throw new CustomException("当前已关联菜品信息，不可删除");
        }
        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Setmeal::getCategoryId,id);
        int count1=setmealService.count(lambdaQueryWrapper);
        if (count1>0){
            throw new CustomException("当前已关联套餐信息，不可删除");
        }
        super.removeById(id);
    }


}
